from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from .models import User
from .serializers import UserSerializer
import jwt
import datetime
from django.conf import settings


# Create your views here.
'''
封装用户注册接口：POST 
①参数说明：username, email, password为必填项，代码体现必填项校验。 
②逻辑要求： 
a)如果email已注册，返回合理的提示和状态码，（提示信息一定要合理，否则没分）。 
b)注册成功后，返回用户详情，不包含password字段，截图返回信息。
c）返回信息中包含token，
d）token，写入本地缓存
'''


class RegisterView(APIView):
    def post(self, request):
        # 注册用户序列化
        serializer = UserSerializer(data=request.data)
        # 验证数据
        if serializer.is_valid(raise_exception=True):
            # 检查邮箱是否已注册
            if User.objects.filter(email=serializer.validated_data['email']).exists():
                return Response({
                    'message': '邮箱已注册'
                }, status=status.HTTP_400_BAD_REQUEST)
            # 保存刚创建的用户
            user = serializer.save()

            # 生成 JWT token
            token = jwt.encode(
                {
                    'username': user.username,
                    'exp': datetime.datetime.utcnow() + datetime.timedelta(days=7)
                },
                settings.SECRET_KEY,
                algorithm='HS256'
            )

            return Response({
                'message': '注册成功',
                'token': token,
                'user': {
                    "username": user.username,
                    "email": user.email,
                    "is_active": user.is_active,
                    "create_time": user.create_time
    }
            }, status=status.HTTP_201_CREATED)

        # 如果验证失败，返回错误信息
        # return Response({
        #     'message': '注册失败',
        #     'errors': serializer.errors
        # }, status=status.HTTP_400_BAD_REQUEST)